package jp.sourceforge.akjrcp.ffmpeg;

import com.akjava.lib.standards.process.ProcessMonitor;

import java.io.IOException;
import java.io.PrintWriter;

import jp.sourceforge.akjrcp.util.PrintStreamProcessPrinter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;




public class FFMpegPCMPipeReader implements Runnable{
	  public static Log log=LogFactory.getLog(FFMpegPCMPipeReader.class);
	PCMPipeReader wavPipeReader;
	private String[] command;
	private Process process;
	ProcessListener processListener;

	public FFMpegPCMPipeReader(String ffmpegPath,String inputPath,int rate,int channel){
		command=FFMpegCommandUtil.makePCMOutputPipeCommand(ffmpegPath,inputPath,rate,channel);
		}
	
	public void run() {
		Runtime runtime=Runtime.getRuntime();
		try {
			process = runtime.exec(command);
			String c="";
			for(int i=0;i<command.length;i++){
				c+="\""+command[i]+"\""+" ";
				}
			log.info("command:"+c);
			
			PrintStreamProcessPrinter printer=new PrintStreamProcessPrinter(new PrintWriter(System.out));//todo can change
			//DoNothingProcessPrinter printer=new DoNothingProcessPrinter();
			ProcessMonitor monitor=new ProcessMonitor(process,printer);
			monitor.setMonitorInput(false);//stop read input.
			monitor.startMonitor();
			
			wavPipeReader=new PCMPipeReader(process.getInputStream());
			if(processListener!=null){
				processListener.started();
			}
			try {
				process.waitFor();
				synchronized(this){
					wavPipeReader.setDone(true);
				}
				
				
				if(processListener!=null){
					processListener.finished();
				}
				//process.destroy();//
				//log.inforead process finished");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void cancel(){
		if(process!=null){
			process.destroy();
		}
	}
	
	public void close() throws IOException{
		if(wavPipeReader!=null){
			wavPipeReader.close();
		}
	}

	public String[] getCommand() {
		return command;
	}

	public void setCommand(String[] command) {
		this.command = command;
	}



	public Process getProcess() {
		return process;
	}

	public void setProcess(Process process) {
		this.process = process;
	}

	public ProcessListener getProcessListener() {
		return processListener;
	}

	public void setProcessListener(ProcessListener processListener) {
		this.processListener = processListener;
	}

	public PCMPipeReader getPCMPipeReader() {
		return wavPipeReader;
	}
/*
	public void setWavPipeReader(WavPipeReader wavPipeReader) {
		this.wavPipeReader = wavPipeReader;
	}*/




}
